from flask_restful import Resource, reqparse
from flask import request
from flask_shop import models, db
from flask_shop.category import cate_api, attr_api


class Categories(Resource):
    def get(self):
        try:
            level = request.args.get("level")
            pnum = request.args.get("pnum")
            psize = request.args.get("psize")
            if level:
                level = int(level)
            else:
                level = 3

            # 获取所有的分类信息
            base_query = models.Category.query.filter(models.Category.level == 1)
            if all([pnum, psize]):
                cates = base_query.paginate(page=int(pnum), per_page=int(psize))
            else:
                cates = base_query.all()
            # cates = models.Category.query.filter(models.Category.level == 1).all()
            # 定义一个列表，存储分类信息
            cate_list = self.to_tree(cates, level)
            return {"status": 200, "msg": "获取分类成功", "data": cate_list}
        except Exception as e:
            print(e)

    def to_tree(self, info: list, level):
        info_list = []
        for i in info:
            i_dict = i.to_dict()
            if i.level < level:
                i_dict["children"] = self.to_tree(i.children, level)
            info_list.append(i_dict)
        return info_list

    def post(self):
        try:
            # 创建ReuqestParser对象
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument("name", type=str, required=True)
            parser.add_argument("level", type=int, required=True)
            parser.add_argument("pid", type=int)
            # 解析参数
            args = parser.parse_args()
            # 判断pid是否传递
            if args.get("pid"):
                c = models.Category(
                    name=args.get("name"), level=args.get("level"), pid=args.get("pid")
                )
            else:
                c = models.Category(name=args.get("name"), level=args.get("level"))
            # 保存到数据库
            db.session.add(c)
            db.session.commit()
            return {"status": 200, "msg": "添加分类成功"}
        except Exception as e:
            print(e)
            return {"status": 500, "msg": "添加分类失败"}


cate_api.add_resource(Categories, "/categories/")


class Attributes(Resource):
    def get(self):
        #  创建一个RequestParser对象
        parser = reqparse.RequestParser()
        # 添加参数
        parser.add_argument("cid", type=int, required=True, location="args")
        parser.add_argument("_type", type=str, required=True, location="args")
        # 解析参数
        args = parser.parse_args()
        # 根据cid 获取分类信息
        cate = models.Category.query.get(args.get("cid"))
        # 获取分类下的所有属性信息
        attr_list = []
        if args.get("_type") == "static":
            attr_list = [a.to_dict() for a in cate.attrs if a._type == "static"]
        elif args.get("_type") == "dynamic":
            attr_list = [a.to_dict() for a in cate.attrs if a._type == "dynamic"]
        return {"status": 200, "msg": "获取属性成功", "data": attr_list}

    def post(self):
        try:
            # 创建一个RequestParser对象
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument("name", type=str, required=True)
            parser.add_argument("val", type=str)
            parser.add_argument("_type", type=str, required=True)
            parser.add_argument("cid", type=int, required=True)
            # 解析参数
            args = parser.parse_args()

            if args.get("val"):
                c = models.Attribute(
                    name=args.get("name"),
                    val=args.get("val"),
                    _type=args.get("_type"),
                    cid=args.get("cid"),
                )
            else:
                c = models.Attribute(
                    name=args.get("name"), _type=args.get("_type"), cid=args.get("cid")
                )
            # 保存到数据库
            db.session.add(c)
            db.session.commit()
            return {"status": 200, "msg": "添加属性成功"}
        except Exception as e:
            print(e)
            return {"status": 500, "msg": "添加属性失败"}


attr_api.add_resource(Attributes, "/attributes/")


class Attribute(Resource):
    def get(self, id):
        try:
            # 根据id 获取数据
            attr = models.Attribute.query.get(id)
            return {"status": 200, "msg": "获取属性成功", "data": attr.to_dict()}
        except Exception as e:
            print(e)
            return {"status": 500, "msg": "获取属性失败"}

    def put(self, id):
        try:
            attr = models.Attribute.query.get(id)
            # 创建一个RequestParser对象
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument("name", type=str)
            parser.add_argument("val", type=str)
            parser.add_argument("_type", type=str)
            parser.add_argument("cid", type=int)
            # 解析参数
            args = parser.parse_args()
            if args.get("name"):
                attr.name = args.get("name")
            if args.get("val"):
                attr.val = args.get("val")
            if args.get("_type"):
                attr._type = args.get("_type")
            if args.get("cid"):
                attr.cid = args.get("cid")
            # 提交到数据库
            db.session.commit()
            return {"status": 200, "msg": "修改属性成功"}
        except Exception as e:
            print(e)
            return {"status": 500, "msg": "修改属性失败"}
    def delete(self,id):
        try:
            attr = models.Attribute.query.get(id)
            db.session.delete(attr)
            db.session.commit()
            return {"status": 200, "msg": "删除属性成功"}
        except Exception as e:
            print(e)
            return {"status": 500, "msg": "删除属性失败"}
attr_api.add_resource(Attribute, "/attribute/<int:id>/")
